package cn.xsly.ymcc.exception;

import cn.xsly.ymcc.enums.ErrorCode;
import cn.xsly.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobleExceptionHandler {
    @ExceptionHandler(GlobleException.class)
    public JSONResult GlobleException(GlobleException e, HttpServletRequest request) {
        log.info(e.getMessage(), request.getRequestURI());
        e.printStackTrace();
        return JSONResult.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public JSONResult Exception(Exception e, HttpServletRequest request) {
        log.info(e.getMessage(), request.getRequestURI());
        e.printStackTrace();
        return JSONResult.error(ErrorCode.SYSTEM_ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
            StringBuffer buffer = new StringBuffer();
        List<ObjectError> s = e.getBindingResult().getAllErrors();
       for(ObjectError obj:s){
           buffer.append(obj.getDefaultMessage()).append(";");
       }


        return JSONResult.error(buffer.toString());
    }
}
